package org.hepeng.workx.spring.session.redis.serializer;

import javassist.ClassPool;
import javassist.CtClass;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @author he peng
 */
public abstract class AbstractSafetyRedisHttpSessionMessageReceiver implements SafetyRedisHttpSessionMessageReceiver {

    protected RedisSerializer serializer;

    public AbstractSafetyRedisHttpSessionMessageReceiver(RedisSerializer serializer) {
        this.serializer = serializer;
    }

    @Override
    public void receiveMessage(String message) throws Exception {
        byte[] classBytes = Base64.decodeBase64(message);
        InputStream in = new ByteArrayInputStream(classBytes);
        CtClass ctClass = ClassPool.getDefault().makeClassIfNew(in);
        String className = ctClass.getName();
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            handleClassBytes(className , classBytes);
        } finally {
            ctClass.detach();
            FileUtils.copyInputStreamToFile(new ByteArrayInputStream(classBytes)
                    , new File(SafetyRedisSerializerConfiguration.CLASSES_DIR + className));
        }
    }

    protected abstract void handleClassBytes(String className , byte [] classBytes);
}
